import React, { FC, ReactElement, useRef } from 'react';
import { ITodo } from '../../../../types/todo';

/** 先定义当前组件接收的props类型 */
interface IProps{
  todoList:ITodo[],
  addTodo:(todo:ITodo)=>void
}
const TodoInput:FC<IProps> = (
  {
    todoList,
    addTodo
  }
):ReactElement => {
  /** ref钩子函数，可以获取指定的dom元素，下面借助泛型将dom元素的类型固定住*/
  const inputRef = useRef<HTMLInputElement>(null)
  const addItem = ():void => {
    const content:string = inputRef.current!.value.trim();
    if (!content) {
      return
    }
    if (todoList && todoList.length > 0) {
        let exists = todoList.find(todo=>content === todo.content)
        if (exists){
          return alert("待办事项已存在1")
        }
    }
    addTodo({
      id:new Date().getTime(),
      content:content,
      completed:false
    })
    inputRef.current!.value = ''
  }
  return (
    <div className="todo-input">
        <input 
          type="text" 
          placeholder='请输入待办项....'
          ref={inputRef}
        />
        <button className='todo-input-btn' onClick={addItem}>添加</button>
    </div>
  )
}
export default TodoInput;